import axios from 'axios'
import qs from 'qs'
import { Dialog, Toast, Notify } from 'vant'
let isProduction = process.env.NODE_ENV === 'production'
// 如果是生产环境
let baseURL = isProduction
  ? 'https://apis.map.qq.com'
  : 'http://192.168.1.105:8080'
// create an axios instance
const service = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  // withCredentials: true,
  timeout: 10000
})
service.interceptors.request.use(
  (config) => {
    Toast({
      duration: 0,
      forbidClick: true,
      message: '',
      icon: 'location-o'
    })
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    Toast.clear()
    if (res.status === 0) {
      return res
    } else {
      Notify({
        type: 'danger',
        message: res.message,
        duration: 1000 * 2
      })
      return Promise.reject(res)
    }
  },
  (error) => {
    Notify({
      type: 'danger',
      message: '网络有误',
      duration: 1000 * 5
    })
    Toast.clear()
    return Promise.reject(error)
  }
)

function ajax(type, url, data = {}) {
  if (Object.prototype.toString.call(data) === '[object Object]') {
    data = qs.stringify(data)
  }
  return service({
    url,
    method: 'post',
    data
  })
}
export function post(url, data = {}) {
  return ajax('post', url, data)
}
export function put(url, data = {}) {
  return ajax('put', url, data)
}
export function del(url, data = {}) {
  return ajax('delete', url, data)
}
export function get(url, data = {}) {
  return service({
    url,
    method: 'get',
    params: {
      ...data,
      key: 'VYKBZ-AAF3U-NHBVL-BKPFE-MTOIO-EDBDH'
    }
  })
}
